package meiyunting.shiwuzhaoling.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 简单负载均衡测试控制器
 */
@RestController
@RequestMapping("/api/simple-lb")
public class SimpleLoadBalancerTestController {

    @Autowired
    private RestTemplate restTemplate;
    
    @Value("${server.port}")
    private String serverPort;
    
    /**
     * 返回当前实例的端口号
     */
    @GetMapping("/port")
    public Map<String, Object> getPort() {
        Map<String, Object> result = new HashMap<>();
        result.put("port", serverPort);
        System.out.println("【简单测试】当前端口: " + serverPort);
        return result;
    }
    
    /**
     * 调用服务实例并返回端口号
     */
    @GetMapping("/test")
    public Map<String, Object> testLoadBalancer() {
        Map<String, Object> result = new HashMap<>();
        
        System.out.println("【简单测试】从端口 " + serverPort + " 发起请求");
        
        // 使用服务名称调用，触发负载均衡
        Map response = restTemplate.getForObject("http://lost-found-service/api/simple-lb/port", Map.class);
        
        result.put("sourcePort", serverPort);
        result.put("targetPort", response.get("port"));
        
        System.out.println("【简单测试】请求从端口 " + serverPort + " 路由到端口 " + response.get("port"));
        
        return result;
    }
} 